package com.cxb.receiver;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.cxb.MainActivity;
import com.cxb.R;
import com.cxb.entity.SMS;
import com.cxb.manager.CxbEventBus;
import com.cxb.manager.SMSManager;

/**
 * @ClassName: SMSReceiver
 * @Description: ���ն���
 * @author ��� 45154139@qq.com
 * @date 2013-10-23 ����10:32:19
 * 
 */
public class SMSReceiver extends BroadcastReceiver {

	SMSManager smsManager = null;
	List<SMS> list = null;

	@Override
	public void onReceive(Context context, Intent intent) {

		smsManager = new SMSManager(context);
		Bundle bundle = intent.getExtras();
		Object[] pdus = (Object[]) bundle.get("pdus");
		list = smsManager.dealSMSofReceiver(pdus);

		boolean skipFlag = false;
		for (SMS msg : list) {
			// /************************* 配合后台bug ***********************/
			// //
			// msg.smsbody="01825218710AIPZ01E113.087039,N28.013063,长沙石燕湖生态公园";
			// String message = msg.smsbody;
			//
			//
			// if (message.length() > 16 && message.subSequence(2,
			// 4).equals("82")) {
			//
			// if (message.contains("02") || message.contains("01")) {
			//
			// int index = message.indexOf("02", 14);
			// if (index == -1 || index > 15) {
			// index = message.indexOf("01", 14);
			// }
			// if (index > 0) {
			// String str = message.substring(0, index);
			// if (str.length() > 14) {
			// if (str.startsWith("0182")) {
			// skipFlag = true;
			// msg.smsbody = message.replaceFirst("0182.{1}",
			// "0182");
			//
			// }
			// }
			// }
			// }
			// } else if (message.length() > 16
			// && message.subSequence(2, 4).equals("8F")) {
			//
			// if (message.length() > 27) {
			//
			// if (message.startsWith("018F")) {
			// skipFlag = true;
			// msg.smsbody = message.replaceFirst("018F.{1}", "018F");
			// }
			// }
			// }
			// /************************************************/
			// TODO 里到时得加过滤，不是所有短信都保存
			skipFlag = false;
			if (skipFlag) {// ����һ��ָ����ţ������̨����
			} else {// ��ͨ����

				// 收到指令短信
				if (isInstructMessage(msg.smsbody)) {
					smsManager.analysisDataFromSms(msg.smsbody);
					return;
				}

//				MainActivity.tts.speak(context
//						.getString(R.string.receive_a_new_sms));

				smsManager.addSMS(msg);
				CxbEventBus.getCxbBus(CxbEventBus.EVENT_MESSAGE_CHANGE).post(msg);
			

			}
			abortBroadcast();
		}

		
	}

	/**
	 * 这是一条指令短信
	 * 
	 * @param message
	 * @return
	 *         陈伟斌
	 *         2014-3-18
	 */
	public boolean isInstructMessage(String message) {
		if (message == null || message.length() < 16) {
			return false;
		}

		// 八字符控制密钥
		int index = 0;
		for (int i = 0; i < 4; i++) {
			index += message.charAt(6 + i) - '0';
			if (message.charAt(6 + 4 + i) != 'A' + index - 1) {
				return false;
			}
		}
		return true;

	}
}
